import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Icon, Card, Button, message, Modal,Form,Input,Tooltip,Spin } from 'antd';
import router from 'umi/router';
//import NumberInfo from '@/components/NumberInfo';
//import QRcode from '@/components/QRcode';
import styles from './index1.less';
const FormItem=Form.Item;
const QRCode = require('qrcode.react');
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
    md: { span: 20 },
  },
};
const HandleForm = props => {
  const {  _this } = props;
  const { versionInfo ,form,dispatch, match} = _this.props;
  const { getFieldDecorator, getFieldValue,setFieldsValue }=form;
  const {qrurl}=_this.state;
 // let path = versionInfo && versionInfo.Debug ? versionInfo.Debug.Url : null;
  const { modalVisible, modalFooter, type } = _this.state;
  const okHandle = () => {
    if (type == 1) {
      dispatch({
        type: 'xcxversionmanage/UndocodeAudit',
        payload:{
          id:versionInfo.Debug.AuditId
        },
        callback: {
          success: (res) => {
            if(res.Code==0){
              message.success('撤销成功');
            handleModalVisible();
            setTimeout(()=>{
              dispatch({
                type: 'xcxversionmanage/GetVersionInfo',
              });
            },1500)
            }else{
              message.error(res.Msg);
            }
          },
        },
      });
    } else if(type==3) {
      form.validateFieldsAndScroll((err, values) => {
        if (err) return;
        dispatch({
          type: 'xcxversionmanage/BindTester',
          payload:{
            wechartId:values.wechartId
          },
          callback: {
            success: (res) => {
              if(res.Code==0){
                message.success('绑定成功');
              handleModalVisible();
              }else{
                message.error(res.Msg);
              }
            },
          },
        });
      })
    }else{
      handleModalVisible();
    }
  };
  const handleModalVisible = () => {
    _this.setState({
      modalVisible: false,
    });
    if(type==3){
      setFieldsValue({
        wechartId:''
      })
    }
  };
  const bind=(
    <Form style={{ marginTop: 8 }} >
            <FormItem {...formItemLayout} hideRequiredMark label="微信号">
              {getFieldDecorator('wechartId', {
                 rules: [
                   { required: true, message: '请输入微信号'}],
              })(<Input placeholder="请输入微信号" style={{ width: '100%' }} />)}
            </FormItem>
    </Form>
  );
  const repeal =(
    <div>
      <p>每天最多可撤销一次，每月最多可撤销10次。确定撤销该版本？</p>
     </div>
  );
  const preview =(
    <div style={{textAlign:'center'}}>
      <div style={{}}><Icon type="check-circle" theme="filled" style={{fontSize:'56px',color:'#52C41A'}}/></div>
      <div style={{fontSize:'24px',marginTop:'16px',marginBottom:'16px',color:'#262626'}}>体验版已生效</div>
      <div style={{marginBottom:'24px',color:'#595959'}}>管理员体验者可扫描下方二维码体验此版本</div>
      <div style={{padding: "24px 0",margin:'0 24px',backgroundColor:'#FAFAFA'}}>
        {qrurl?<QRCode id="canvas" size={124} value={qrurl}/>:null}
        <div style={{margin:'16px 0'}}><a href="" download="qrcode.png" id="downBtn" style={{marginRight:'8px'}}>下载二维码</a></div> {/** <a href="javascript:void(0)">网页端预览</a>* */}
        <div><span style={{color:'#595959'}}>还没添加体验者，</span><Link to={`/${match.params.storeId}/wechat/miniapp/experiencer`}>点击添加</Link></div>
      </div>
    </div>
  );
  return (
    <Modal
      title={type == 1 ? '撤销' : type==2?'版本预览':'绑定体验者'}
      visible={modalVisible}
      onCancel={handleModalVisible}
      onOk={okHandle}
      cancelText="关闭"
      className={`${type==2?styles.preview:''}`}
      footer={type===2?null:[
        <Button key="cancel" onClick={handleModalVisible}>取消</Button>,
        <Button key="submit" type="primary" onClick={okHandle}>
          确认
        </Button>,
      ]}
    >
      {/* {type == 1 ? '确定撤销该版本？' : <QRcode QR_path={path} />} */}

  {type==1?repeal:type==2?preview:type==3?bind:null}
    </Modal>
  );
};
@connect(({ xcxversionmanage, loading }) => ({
  xcxversionmanage,
  versionInfo: xcxversionmanage.versionInfo,
  updateLoading:loading.effects['xcxversionmanage/Commit'],
  ReleaseLoading:loading.effects['xcxversionmanage/Release'],
  SubmitForAuditLoading:loading.effects['xcxversionmanage/SubmitForAudit'],
  repealLoading:loading.effects['xcxversionmanage/UndocodeAudit'],
  loadingWxaCode:loading.effects['xcxversionmanage/GetWxaCode'],
}))
@Form.create()
export default class Analysis extends Component {
  state = {
    salesType: 'all',
    type:'',
    currentTabKey: '',
    modalVisible: false,
    qrurl:'',
    status:1,
    QRurl:'',
    loading: true
  };

  componentWillMount() {
    window.Isoption = false;
    const { dispatch } = this.props;
    dispatch({
      type: `xcxauth/GetAuthStatus`,
      callback: {
          success: (data) => {
              if (data.Code !== 0) {
                  router.replace({
                      pathname: `/${window.storeId}/wechat/miniapp`,
                  });
              } else {
                dispatch({
                  type: 'xcxversionmanage/GetVersionInfo',
                  callback: {
                    success: (res)=>{
                      this.setState({
                        loading: false,
                      });
                    }
                  }
                });
              }
          }
      }
    });

  }
  componentDidMount() {
    window.Isoption = true;
  }
  preview = (type) => {
    const { versionInfo } = this.props;
    if(type==1){
      this.setState({
        qrurl:`https://open.weixin.qq.com/sns/getexpappinfo?appid=${versionInfo.Development.QrCode}&iswxtpa=1#wechat-redirect`,
      })
    }else{
      this.setState({
        qrurl:`https://open.weixin.qq.com/sns/getexpappinfo?appid=${versionInfo.Debug.QrCode}&iswxtpa=1#wechat-redirect`,
      })
    }
    this.show(2);
  };
  canvasToImage = () => {
    const canvas=document.getElementById("canvas");
    document.getElementById("downBtn").href = canvas.toDataURL();
  }

  //立即发布
  Release = () =>{
    const { versionInfo, dispatch } = this.props;
    dispatch({
      type: 'xcxversionmanage/Release',
      callback: {
        success: (res) => {

          if(res.Code==0){
            message.success('发布成功');
          setTimeout(()=>{
            dispatch({
              type: 'xcxversionmanage/GetVersionInfo',
            });
          },1500)
           }else{
            message.error("发布失败，该程序已发布。"+res.Msg);
           }
        },
      },
    });
  }
  //立即更新//上传代码
  update = () => {
    const { versionInfo, dispatch } = this.props;
    dispatch({
      type: 'xcxversionmanage/Commit',
      payload:{
        templateId:versionInfo.Development.TemplateId
      },
      callback: {
        success: (res) => {
          if(res.Code==0){
            message.success('更新成功');
            setTimeout(()=>{
              dispatch({
                type: 'xcxversionmanage/GetVersionInfo',
              });
            },1500)
           }else{
            message.error(res.Msg);
           }
        },
      },
    });
  };
  //提交审核
  SubmitForAudit = () =>{
    const { versionInfo, dispatch } = this.props;
    dispatch({
      type: 'xcxversionmanage/SubmitForAudit',
      callback: {
        success: (res) => {
          if(res.Code==0){
            message.success('提交审核成功');
            setTimeout(()=>{
              dispatch({
                type: 'xcxversionmanage/GetVersionInfo',
              });
            },1500)
           }else{
            message.error(res.Msg);
           }
        },
      },
    });
  }
  //撤销审核
  repeal = () => {
    const { versionInfo, dispatch } = this.props;
    // this.setState({
    //   type:1
    // },()=>{
    //   this.show(1);
    // })
    this.show(1);
    console.log(versionInfo.Debug);
  };
  //绑定体验者
  BindTester = ()=>{
    const { versionInfo, dispatch } = this.props;
    this.show(3);
    // dispatch({
    //   type: 'xcxversionmanage/BindTester',
    //   callback: {
    //     success: (res) => {
    //       if(res.Code==0){
    //         message.success('绑定成功');
    //       }else{
    //         message.error(res.Msg);
    //       }
    //     },
    //   },
    // });
  }
  //更新小程序码
  GetWxaCode = ()=>{
    const { versionInfo, dispatch } = this.props;
    dispatch({
      type: 'xcxversionmanage/GetWxaCode',
      callback: {
        success: (res) => {
         if(res.Code==0){
          message.success('更新小程序码成功');
          this.setState({
            QRurl:res.Data.ImgUrl
          })
         }else{
          message.error(res.Msg);
         }
        },
      },
    });
  }
  show = type => {
    this.setState({
      type,
      modalVisible: true,
    });
    // setTimeout(()=>{
    //   this.canvasToImage();
    // },3000)
  };
  render() {
    let { xcxversionmanage, versionInfo,loadingWxaCode,updateLoading,ReleaseLoading,SubmitForAuditLoading,repealLoading } = this.props;
    const {loading} = this.state;
    const {Release, Debug, Development }= versionInfo
    return (
      <Fragment>
        <Spin spinning={loading}>
        <div className={styles.Mycard}>
        <Card bordered={false} >
        <div className={styles.versionBlock}>
          <div className={styles.Title}>
            <div style={{position:'relative',display:'inline-block'}}>
              <span>线上版本</span>
              <Tooltip title="系统当前使用中的小程序版本"><Icon type="question-circle" theme="filled" style={{color:'#ccc',position:'absolute',top:4,right:-18}}/></Tooltip>
            </div>
          </div>
          {Release&&Release.Version?<div style={{marginBottom:'16px'}}>
            <div className={styles.versionNum}>{Release.Version}</div>
            <div style={{color:'rgba(0, 0, 0, 0.45)'}}>于{Release.CreateTime}创建版本</div>
            <div style={{marginTop:'24px'}}>
              <img src={Release.QrCodeUrl} style={{width:124,height:124}}/>
            </div>
          </div>:
          <div className={styles.notVersion}>― 尚未提交线上版本 ―</div>}
        </div>
        <div className={styles.versionBlock}>
          <div className={styles.Title}>
            <div style={{position:'relative',display:'inline-block'}}>
              <span>审核版本</span>
              <Tooltip title="提交至微信官方审核的小程序版本"><Icon type="question-circle" theme="filled" style={{color:'#ccc',position:'absolute',top:4,right:-18}}/></Tooltip>
            </div>
          </div>
          {Debug&&Debug.Version?
          <Fragment>
            <div style={{marginBottom:'16px'}}>
              <div className={styles.versionNum}>{Debug.Version}</div>
              <div style={{color:'rgba(0, 0, 0, 0.45)'}}>于{Debug.CreateTime}提交审核</div>
            </div>
            <div>
              <p className={styles.hasNewVerson}>{Debug.StatuName==='审核中'?
              '微信审核中，请耐心等待。一般审核周期为1-7个工作日，审核成功后将自动发布。':
              Debug.StatuName==='审核失败' || Debug.StatuName==='撤回'?`审核失败，${Debug.Reason}`:
              Debug.StatuName==='审核成功'?`审核成功，自动发布失败，请点击“立即发布”按钮重新发布。${Debug.Reason}`:
              Debug.StatuName==='待发布'?`发布失败。${Debug.Reason}`:''}</p>
              <Button style={{marginRight:'8px'}} onClick={() => this.preview(2)}>版本预览</Button>
              {Debug.StatuName==='待发布' || Debug.StatuName==='审核成功' || Debug.StatuName==='发布失败'?<Button type="primary" onClick={() => this.Release()} loading={ReleaseLoading}>立即发布</Button>:
              Debug.StatuName==='审核失败' || Debug.StatuName==='撤回'?<Button type="primary" onClick={() => this.SubmitForAudit()} loading={SubmitForAuditLoading}>重新审核</Button>:
              <Button onClick={() => this.repeal()} loading={repealLoading}>撤销审核</Button>}
            </div>
          </Fragment>:
        <div className={styles.notVersion}>― 暂无版本提交审核 ―</div>}
        </div>
        <div className={styles.versionBlock}>
          <div className={styles.Title}>
            <div style={{position:'relative',display:'inline-block'}}>
              <span>系统最新版本</span>
              <Tooltip title="系统小程序最新可用版本"><Icon type="question-circle" theme="filled" style={{color:'#ccc',position:'absolute',top:4,right:-18}}/></Tooltip>
            </div>
          </div>
          {Development&&Development.Version?
          <Fragment>
            <div style={{marginBottom:'16px'}}>
              <div className={styles.versionNum}>{Development.Version}</div>
              <div style={{color:'rgba(0, 0, 0, 0.45)'}}>于{Development.CreateTime}创建版本</div>
            </div>
            {Development.HasNew?<div>
              {Debug&&Debug.StatuName==='审核中' && Development.StatuName==='待升级'?<Fragment>
                <p className={styles.hasNewVerson}>当前系统已有新的版本，但暂时无法更新，请等待当前审核中版本审核完毕或撤销当前审核版本</p>
                <Button disabled>立即上传</Button>
              </Fragment>:
              <Fragment>
                <p className={styles.hasNewVerson}>{Development.StatuName==='上传失败'?`上传失败，${Development.Reason}`:
                Development.StatuName==='上传成功'?'小程序更新上传成功，请点击“提交审核”按钮，提交至微信官方进行审核；建议提交审核前先点击“版本预览”按钮进行预览，如果您没有体验权限，请在“体验者管理”中添加体验者。':
                '当前系统已有新的版本，可点击下方按钮，上传最新版本代码。'}
                </p>
                {Development.StatuName==='上传失败'?<Button type="primary" onClick={() => this.update()} loading={updateLoading}>重新上传</Button>:
                Development.StatuName==='上传成功'?<Fragment><Button style={{marginRight:'8px'}} onClick={() => this.preview(1)}>版本预览</Button><Button type="primary" onClick={() => this.SubmitForAudit()} loading={SubmitForAuditLoading}>提交审核</Button></Fragment>:
                <Button type="primary" onClick={() => this.update()} loading={updateLoading}>立即上传</Button>
                }
              </Fragment>}
            </div>:<div>暂无版本需要更新</div>}
          </Fragment>:
        <div className={styles.notVersion}>― 尚未提交线上版本 ―</div>}
        </div>
        </Card>
        </div>
        </Spin>
        <HandleForm _this={this} />
      </Fragment>
    );
  }
}
